package cn.ustb.controller;

import cn.ustb.entity.User;
import cn.ustb.service.UserService;
import cn.ustb.serviceImpl.UserServiceImpl;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static cn.ustb.util.MD5WithSaltUtil.generateSaltPassword;
import static cn.ustb.util.MD5WithSaltUtil.verifySaltPassword;

/**
 * @author 柒叁
 */
@WebServlet("/modifyPasswordServlet")
public class ModifyPasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String oldpassword = request.getParameter("oldpassword");
        String newpassword = request.getParameter("newpassword");
        String confirmpassword = request.getParameter("confirmpassword");
        //修改密码
//        update(user,newpassword);
        if("".equals(oldpassword)){
            session.setAttribute("message", "旧密码不能为空！");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }else if("".equals(newpassword)){
            session.setAttribute("message", "新密码不能为空！");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }else if("".equals(confirmpassword)) {
            session.setAttribute("message", "请确认新密码！");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }else if(!verifySaltPassword(oldpassword,user.getPassword())){
            session.setAttribute("message", "旧密码有误！");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }else if(!newpassword.equals(confirmpassword)){
            session.setAttribute("message", "两次密码输入不一致！");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }else{
            user.setPassword(generateSaltPassword(newpassword));
            UserService userService=new UserServiceImpl();
            userService.update(user);
            session.setAttribute("message", "修改密码成功");
            response.sendRedirect(request.getContextPath() + "/modifypassword.jsp");
        }

    }
}
